package Team.Yaohuo.listener;


import Team.Yaohuo.config.ThreadLocalConfig;
import Team.Yaohuo.constant.JDYConstant;
import Team.Yaohuo.utils.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 消息队列监听简道云代办 判断
 */
@Component
@Slf4j
public class RabbitListenerWait {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WxUtil wxUtil;
    @Autowired
    private HttpServletRequest httpServletRequest;

    private Integer count = 1;
    private static final String MEG_PUSH_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";



    /**
     * 监听消息 是否有 如果有则进行消息推送服务
     */
    @RabbitListener(queues = "messageQueue")
    public void waitMessageListener(List<Map> tasks) {
        String userId = ThreadLocalConfig.getCurrentId();
        HttpSession session = httpServletRequest.getSession();
        Map<String, Object> waitMapJdy = new HashMap<>();
        // 当没有代办时
        if (tasks.size() == 0) {
            waitMapJdy.put("form_title", "无");
            waitMapJdy.put("url", "无");
        } else {
            for (int i = 0; i < 1; i++) {
                // 代办名称
                String formTitle = (String) tasks.get(i).get("form_title");
                // 代办网页地址
                String waitUrl = (String) tasks.get(i).get("url");
                waitMapJdy.put("form_title", formTitle);
                waitMapJdy.put("url", waitUrl);
            }
        }
        // 简道云消息代办推送
        Map<String, Object> waitMapJdyMap = wxUtil.messagePushTextTypeWaitJDY(userId, waitMapJdy, tasks.size() + "");
        HttpEntity<Map<String, Object>> http = new HttpEntity<>(waitMapJdyMap);
        ResponseEntity<Map> response = restTemplate.exchange(MEG_PUSH_URL + "?access_token=" + session.getAttribute("access_token"), HttpMethod.POST, http, Map.class);
        if (response.getBody() != null) {
            Integer errcode = (Integer) response.getBody().get("errcode");
            String msgid = (String) response.getBody().get("msgid");
            if (errcode == 0) {
                log.info("消息推送成功，当前megId为:{}", msgid);
            } else {
                log.error("消息推送失败，返回错误码为:{}, 请前往https://developer.work.weixin.qq.com/document/path/96213进行查看", errcode);
            }
        }

    }
}
